C# 读写三菱PLC

您所在的位置:网站首页 汇川plc ip地址设定 C# 读写三菱PLC

C# 读写三菱PLC

2023-04-02 23:57| 来源: 网络整理| 查看: 265

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; namespace MitsubishiPLCCommunication { class Program { static void Main(string[] args) { //设定PLC的IP地址和端口号 string ip = "192.168.1.10"; int port = 3000; //连接PLC TcpClient client = new TcpClient(); client.Connect(ip, port); //设定要读写的地址 string address = "D100"; //读取数据 byte[] readCommand = { 0x50, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x04, 0x00, 0x01, 0x12, 0x0a, 0x00, 0x00, 0x00 }; byte[] readAddress = Encoding.ASCII.GetBytes(address); Array.Copy(readAddress, 0, readCommand, 9, 4); NetworkStream stream = client.GetStream(); stream.Write(readCommand, 0, readCommand.Length); byte[] readResponse = new byte[1024]; int bytesRead = stream.Read(readResponse, 0, readResponse.Length); byte[] data = new byte[2]; Array.Copy(readResponse, 15, data, 0, 2); int value = BitConverter.ToInt16(data, 0); Console.WriteLine("The value of {0} is {1}", address, value); //写入数据 int newValue = 123; byte[] writeCommand = { 0x50, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x14, 0x00, 0x01, 0x12, 0x0a, 0x00, 0x00, 0x00 }; byte[] writeAddress = Encoding.ASCII.GetBytes(address); Array.Copy(writeAddress, 0, writeCommand, 9, 4); byte[] writeData = BitConverter.GetBytes(newValue); Array.Copy(writeData, 0, writeCommand, 13, 2); stream.Write(writeCommand, 0, writeCommand.Length); byte[] writeResponse = new byte[1024]; bytesRead = stream.Read(writeResponse, 0, writeResponse.Length); Console.WriteLine("Write operation status: {0}", writeResponse[9]);

//关闭连接 client.Close();

} } } ``` 该示例代码包含以下功能: 1. 连接到三菱PLC的TCP/IP网络。 2. 读取指定地址的数据。 3. 将指定地址的数据写入到PLC。 4. 关闭与PLC的连接。 其中,读取数据和写入数据都需要发送一段特定格式的命令,并从命令的响应中解析出返回的数据。这里使用了C#中的BitConverter类来将字节数组转换为整数类型的数据。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3